var hightlightindex = -1;
$(document).ready(function() {
	var stationInput = $("#input01");
	var stationInputOffset = stationInput.offset();
	var stationdiv = $("#stationdiv");
	stationdiv.css("position", "absolute").css("top",
			stationInputOffset.top + stationInput.height() + "px").css("left",
			stationInputOffset.left).css("width", stationInput.width() + "px");
	stationInput.keyup(function(event) {
				var keyCode = event.keyCode;
				alert(keyCode);
				if ((keyCode >= 65 && keyCode <= 90) || keyCode == 8
						|| keyCode == 46 || keyCode == 32||(keyCode>=48&&keyCode<=57)) {
					var stationText = stationInput.val();
					if (stationText != "") {
						$.post("StationsServlet", {
									stationText : stationText
								}, function(data) {
									var jsonvars = data.stations;
									stationdiv.html("");
									for (var i = 0; i < jsonvars.length; i++) {
										$("<div>").html(jsonvars[i])
												.appendTo(stationdiv);
									}
									if (jsonvars.length > 0) {
										stationdiv.show().css("border", "1px black solid");
									} else {
										stationdiv.hide();
										hightlightindex = -1;
									}
								}, "json");
					} else {
						stationdiv.hide();
						hightlightindex = -1;
					}
				} else if (keyCode == 38 || keyCode == 40) {
					if (keyCode == 40) {
						var childNodes = stationdiv.children("div");
						if (hightlightindex != -1) {
							childNodes.eq(hightlightindex).css(
									"background-color", "white");
						}
						hightlightindex++;
						if (hightlightindex == childNodes.length) {
							hightlightindex = 0;
						}
						childNodes.eq(hightlightindex).css("background-color",
								"#CCC");

					}
					if (keyCode == 38) {
						var childNodes = stationdiv.children("div");
						if (hightlightindex != -1) {
							childNodes.eq(hightlightindex).css(
									"background-color", "white");
							hightlightindex--;
						} else {
							hightlightindex = childNodes.length - 1;
						}
						childNodes.eq(hightlightindex).css("background-color",
								"#CCC");
					}
				} else if (keyCode == 13)
					// keycode 13 = Enter
					if (hightlightindex != -1) {
						var focusText = stationdiv.children("div")
								.eq(hightlightindex).text();
						$("#input01").val(focusText);
						hightlightindex = -1;
					}
			}

	);

});